package com.hejie.commentservice.consumer;

import com.hejie.commentservice.repository.CommentRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Slf4j
public class KafkaCommentConsumer {
    private final CommentRepository commentRepository;
    private final RedisTemplate<String, Object> redisTemplate;
    private static final String CACHE_KEY_VIDEO_COUNT = "comment:count:video:";

    @Autowired
    public KafkaCommentConsumer(CommentRepository commentRepository, RedisTemplate<String, Object> redisTemplate) {
        this.commentRepository = commentRepository;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 监听视频删除事件，批量删除相关评论
     */
    @KafkaListener(topics = "video-deleted-topic", groupId = "comment-service-group")
    @Transactional
    public void handleVideoDeletedEvent(Long videoId) {
        if (videoId == null) {
            log.warn("接收到空的视频ID，忽略处理");
            return;
        }

        try {
            // 逻辑删除该视频的所有评论
            commentRepository.updateStatusByVideoId(videoId);
            // 删除视频评论总数缓存
            redisTemplate.delete(CACHE_KEY_VIDEO_COUNT + videoId);

            log.info("成功处理视频删除事件，视频ID: {}，已批量处理相关评论", videoId);
        } catch (Exception e) {
            log.error("处理视频删除事件失败，视频ID: {}", videoId, e);
            // 可以选择抛出异常让Kafka进行重试
            throw new RuntimeException("处理视频删除事件失败", e);
        }
    }
}